package cool.mtc.security.auth.jwt;

import cool.mtc.security.SecurityProperties;
import cool.mtc.security.handler.auth.jwt.JwtAuthFailureHandler;
import cool.mtc.security.handler.auth.jwt.JwtAuthSuccessHandler;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.stereotype.Component;

/**
 * @author 明河
 */

@Component
@ConditionalOnProperty(value = "mtc.security.auth-jwt.enabled", havingValue = "true", matchIfMissing = true)
@Setter(onMethod = @__(@Autowired))
public class JwtAuthAdapter extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    private SecurityProperties securityProperties;
    private JwtAuthTemplate jwtAuthTemplate;
    private JwtAuthSuccessHandler jwtAuthSuccessHandler;
    private JwtAuthFailureHandler jwtAuthFailureHandler;

    @Override
    public void configure(HttpSecurity http) {
        JwtAuthFilter filter = new JwtAuthFilter(securityProperties);
        filter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        filter.setAuthenticationSuccessHandler(jwtAuthSuccessHandler);
        filter.setAuthenticationFailureHandler(jwtAuthFailureHandler);

        JwtAuthProvider provider = new JwtAuthProvider();
        provider.setAuthTemplate(jwtAuthTemplate);

        http.authenticationProvider(provider)
                .addFilterBefore(filter, LogoutFilter.class);
    }
}
